<template>
	<view class="dynamic-menu">
		<!-- 无菜单权限提示 -->
		<view v-if="processedMenuList.length === 0" class="no-menu-info">
			<text>暂无菜单权限,请联系管理员授权</text>
		</view>
		
		<!-- 动态菜单 -->
		<view v-for="(menuGroup, groupIndex) in processedMenuList" :key="groupIndex">
			<!-- 如果有子分类，每个子分类显示为独立的卡片 -->
			<view v-if="menuGroup.subMenus && menuGroup.subMenus.length > 0">
				<view v-for="(subMenu, subIndex) in menuGroup.subMenus" :key="subIndex" class="sub-menu-card card u-m-b-20">
					<view class="sub-title">{{ subMenu.title }}</view>
					<u-grid class="grid" :col="4" :border="false">
						<u-grid-item v-for="(item, index) in subMenu.items" :key="index" @click="navTo(item.url)">
							<view class="grid-item-content">
								<u-icon :style="{ color: item.color != '' ? item.color : '#000' }" class="grid-icon" :name="item.icon" :size="70"></u-icon>
								<view class="grid-text">{{ item.name }}</view>
							</view>
						</u-grid-item>
					</u-grid>
				</view>
			</view>
			
			<!-- 如果没有子分类，显示为单个卡片 -->
			<view v-else-if="menuGroup.items && menuGroup.items.length > 0" class="menu-group card u-m-b-20">
				<view class="title">{{ menuGroup.title }}</view>
				<u-grid class="grid" :col="4" :border="false">
					<u-grid-item v-for="(item, index) in menuGroup.items" :key="index" @click="navTo(item.url)">
						<view class="grid-item-content">
							<u-icon :style="{ color: item.color != '' ? item.color : '#000' }" class="grid-icon" :name="item.icon" :size="70"></u-icon>
							<view class="grid-text">{{ item.name }}</view>
						</view>
					</u-grid-item>
				</u-grid>
			</view>
		</view>
	</view>
</template>

<script>
/**
 * 动态菜单组件
 * 根据API返回的菜单数据动态生成菜单界面
 */
export default {
	name: 'DynamicMenu',
	props: {
		// 菜单数据，如果为空则自动从API获取
		menuData: {
			type: Array,
			default: () => []
		},
		// 是否显示加载状态
		showLoading: {
			type: Boolean,
			default: true
		},
		// 菜单类型：1-录入，2-报表，3-财务，0-全部
		menuType: {
			type: Number,
			default: 0
		}
	},
	data() {
		return {
			// 处理后的菜单数据
			processedMenuList: [],
			// 图标映射
			iconMap: {
				'财务管理': 'red-packet-fill',
				'假勤管理': 'gift-fill',
				'店铺交款': 'red-packet-fill',
				'工资表': 'red-packet-fill',
				'排休表': 'gift-fill',
				'录入': 'file-text',
				'报表': 'file-text-fill',
				'财务': 'red-packet-fill',
				'销售录入': 'file-text',
				'佣金录入': 'rmb-circle',
				'开支录入': 'minus-circle',
				'报表管理': 'file-text-fill',
				'合买': 'plus-people-fill',
				'帮分店出票': 'heart-fill',
				'给分店出票': 'gift-fill',
				'本店销量': 'file-text',
				'体彩佣金': 'rmb-circle',
				'福彩佣金': 'rmb-circle',
				'即开佣金': 'star-fill',
				'其他佣金': 'plus-circle-fill',
				'销量报表': 'file-text-fill',
				'分店出票统计': 'share-fill',
				'合买出票统计': 'plus-people-fill',
				'佣金报表': 'rmb-circle'
			},
			// 颜色映射
			colorMap: {
				'财务管理': '#2D56B2',
				'假勤管理': '#2D56B2',
				'录入': '#2D56B2',
				'报表': '#2D56B2',
				'财务': '#2D56B2',
				'销售录入': '#2D56B2',
				'佣金录入': '#F43530',
				'开支录入': '#41A863',
				'报表管理': '#2D56B2'
			}
		};
	},
	watch: {
		menuData: {
			handler(newVal) {
				if (newVal && newVal.length > 0) {
					this.processedMenuList = this.processMenuData(newVal);
				}
			},
			immediate: true
		}
	},
	mounted() {
		// 如果没有传入菜单数据，则从API获取
		if (!this.menuData || this.menuData.length === 0) {
			this.loadMenuData();
		}
	},
	methods: {
		// 加载菜单数据
		async loadMenuData() {
			try {
				const res = await this.$u.api.menuRoute();
				
				// 检查不同的数据结构
				if (res && res.children) {
					// 查找"APP菜单授权"菜单项
					const appMenuAuth = res.children.find(item => item.meta && item.meta.title === 'APP菜单授权');
					
					if (appMenuAuth && appMenuAuth.children) {
						this.processedMenuList = this.processMenuData(appMenuAuth.children);
					} else {
						this.processedMenuList = this.getDefaultMenuData();
					}
				} else if (res && res.meta && res.meta.title === 'APP菜单授权' && res.children) {
					// 如果直接返回的就是APP菜单授权数据
					this.processedMenuList = this.processMenuData(res.children);
				} else if (Array.isArray(res)) {
					// 如果API直接返回数组
					this.processedMenuList = this.processMenuData(res);
				} else {
					this.processedMenuList = this.getDefaultMenuData();
				}
			} catch (error) {
				console.error('加载菜单数据失败:', error);
				// 如果API调用失败，使用默认的硬编码菜单
				this.processedMenuList = this.getDefaultMenuData();
			}
		},
		
		// 处理菜单数据，转换为页面显示格式
		processMenuData(menuData) {
			const processedMenus = [];
			
			// 根据menuType参数确定要显示的分类
			let targetCategories = [];
			switch(this.menuType) {
				case 1:
					targetCategories = ['录入'];
					break;
				case 2:
					targetCategories = ['报表'];
					break;
				case 3:
					targetCategories = ['财务'];
					break;
				case 4:
					targetCategories = ['进销存'];
					break;
				case 0:
				default:
					targetCategories = ['录入', '报表', '财务', '进销存'];
					break;
			}
			
			// 找到"APP菜单授权"分类
			const appMenuAuth = menuData.find(category => 
				category.meta && category.meta.title === 'APP菜单授权'
			);
			
			if (!appMenuAuth || !appMenuAuth.children) {
				return processedMenus;
			}
			
			// 为每个目标分类创建对应的菜单数据
			targetCategories.forEach(tabTitle => {
				const subMenus = [];
				
				// 在APP菜单授权的children中寻找对应的分类
				appMenuAuth.children.forEach(category => {
					if (category.meta && category.meta.title === tabTitle && category.children) {
						// 处理二级菜单，保持子分类结构
						category.children.forEach(subCategory => {
							if (subCategory.meta && subCategory.meta.title && subCategory.children) {
								const subCategoryTitle = subCategory.meta.title;
								
								const menuItems = [];
								// 处理三级菜单（具体的功能项）
								subCategory.children.forEach(item => {
									if (item.meta && item.meta.title && item.url) {
										menuItems.push({
											name: item.meta.title,
											icon: this.getIconForMenu(item.meta.title),
											color: this.getColorForMenu(subCategoryTitle),
											url: item.url
										});
									}
								});
								
								// 如果有菜单项，添加到子分类中
								if (menuItems.length > 0) {
									subMenus.push({
										title: subCategoryTitle,
										items: menuItems
									});
								}
							}
						});
					}
				});
				
				// 如果有子分类，添加到结果中
				if (subMenus.length > 0) {
					processedMenus.push({
						title: tabTitle,
						subMenus: subMenus
					});
				}
			});
			
			return processedMenus;
		},
		
		// 获取菜单项对应的图标
		getIconForMenu(menuName) {
			return this.iconMap[menuName] || 'file-text';
		},
		
		// 获取菜单项对应的颜色
		getColorForMenu(categoryName) {
			return this.colorMap[categoryName] || '#2D56B2';
		},
		
		// 获取默认菜单数据（API失败时的备用方案）
		getDefaultMenuData() {
			const allMenus = [
				{
					title: '录入',
					items: [
						{ 
							name: '合买', 
							icon: 'plus-people-fill', 
							color: '#2D56B2',
							url: '/pages/salesManagement/buytogether?type=1' 
						},
						{ 
							name: '帮分店出票', 
							icon: 'heart-fill', 
							color: '#2D56B2',
							url: '/pages/salesManagement/buytogether?type=2' 
						},
						{ 
							name: '给分店出票', 
							icon: 'gift-fill', 
							color: '#2D56B2',
							url: '/pages/salesManagement/buytogether?type=3' 
						},
						{ 
							name: '本店销量', 
							icon: 'file-text', 
							color: '#2D56B2',
							url: '/pages/salesManagement/buytogether?type=4' 
						}
					]
				},
				{
					title: '报表',
					items: [
						{ 
							name: '销量报表', 
							icon: 'file-text-fill', 
							color: '#2D56B2',
							url: '/pages/report/saleReport?type=10' 
						},
						{ 
							name: '分店出票统计', 
							icon: 'share-fill', 
							color: '#2D56B2',
							url: '/pages/report/branchTicketingReport?type=11' 
						},
						{ 
							name: '合买出票统计', 
							icon: 'plus-people-fill', 
							color: '#2D56B2',
							url: '/pages/report/jointTicketingReport?type=12' 
						},
						{ 
							name: '佣金报表', 
							icon: 'rmb-circle', 
							color: '#2D56B2',
							url: '/pages/report/commissionReport?type=13' 
						}
					]
				},
				{
					title: '财务',
					items: [
						{ 
							name: '店铺交款', 
							icon: 'red-packet-fill', 
							color: '#2D56B2',
							url: '/pages/paymentManagement/paymentManagement?type=13' 
						},
						{ 
							name: '工资表', 
							icon: 'red-packet-fill', 
							color: '#2D56B2',
							url: '/pages/paymentManagement/payroll'
						},
						{ 
							name: '排休表', 
							icon: 'gift-fill', 
							color: '#2D56B2',
							url: '/pages/paymentManagement/replacementSummary' 
						}
					]
				}
			];
			
			// 根据menuType参数过滤菜单
			switch(this.menuType) {
				case 1:
					return allMenus.filter(menu => menu.title === '录入');
				case 2:
					return allMenus.filter(menu => menu.title === '报表');
				case 3:
					return allMenus.filter(menu => menu.title === '财务');
				case 0:
				default:
					return allMenus;
			}
		},
		
		navTo(url) {
			uni.navigateTo({
				url: url
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.dynamic-menu {
	.no-menu-info {
		text-align: center;
		padding: 80rpx 40rpx;
		color: #999;
		font-size: 28rpx;
		background-color: #f8f8f8;
		border-radius: 20rpx;
		margin: 20rpx;
	}

	.menu-group {
		background-color: #fff;
		border-radius: 20rpx;
		margin: 20rpx;
		padding: 20rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
		position: relative;
		overflow: hidden;
		
		&::before {
			content: '';
			position: absolute;
			top: -30rpx;
			left: -15%;
			right: -15%;
			height: 120rpx;
			background: linear-gradient(135deg, #ff6b9d 0%, #ff8fab 50%, #ffa8c5 100%);
			border-radius: 50%;
			z-index: 0;
		}
	}

	.title {
		font-size: 24rpx;
		color: #fff;
		margin-bottom: 20rpx;
		padding-left: 10rpx;
		font-weight: 500;
		text-shadow: 0 1rpx 3rpx rgba(0, 0, 0, 0.2);
		position: relative;
		z-index: 1;
	}

	.sub-menu-card {
		background-color: #fff;
		border-radius: 20rpx;
		margin: 20rpx;
		padding: 20rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
		position: relative;
		overflow: hidden;
		
		&::before {
			content: '';
			position: absolute;
			top: -30rpx;
			left: -15%;
			right: -15%;
			height: 120rpx;
			background: linear-gradient(135deg, #ff6b9d 0%, #ff8fab 50%, #ffa8c5 100%);
			border-radius: 50%;
			z-index: 0;
		}
	}

	.sub-title {
		font-size: 34rpx;
		color: #fff;
		margin-bottom: 20rpx;
		padding-left: 10rpx;
		font-weight: 500;
		text-shadow: 0 1rpx 3rpx rgba(0, 0, 0, 0.2);
		position: relative;
		z-index: 1;
		height: 60rpx;
		line-height: 60rpx;
	}

	.grid-item-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 100%;
		padding: 10rpx 0;
		position: relative;
		z-index: 1;
	}

	.grid-icon {
		margin-bottom: 10rpx;
	}

	.grid-text {
		font-size: 26rpx !important;
		color: #000;
		text-align: center;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
}
</style>
